﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using WChat;
using System.Text.RegularExpressions;
using Models;
using DAL;
using System.Runtime;
using System.Threading;

namespace WChat {

    public partial class WinXinBox : UserControl {
        public WXUser _me;
        public  static string _setting;
        //快捷回复权限
        private int _St_CanChat;
        private int Seq = 0;
        public WXUser user;
        //定义委托 头像显示未读消息
        public delegate void UnReadMsgEventHandler(string pageName, string msg);
        public event UnReadMsgEventHandler UnReadMsg;
        //定义委托 设置标签名为微信号昵称
        public delegate void SuccessLoginEventHandler(string name);
        public event SuccessLoginEventHandler Success_Login;
        //定义委托 用于群发助手
        public delegate void NewAllMsgEventHandler(WXUser me, WXUser _user);
        public event NewAllMsgEventHandler NewAllMsg;
        Auto_Reply reply = new Auto_Reply();
        //定义委托 快捷回复权限
        public delegate void QuickReplyEventHandler(int str);
        private Auto_Reply_EventHandler _Areply = new Auto_Reply_EventHandler();
        private bool huifu = false;
        SqlHandle sql = new SqlHandle();
        SqlTest sqllite = new SqlTest(); 
        //当前登录的微信号
        private List<string> Arr;
        public string MyUin;
        private System.Windows.Forms.Timer sync1;  //一定要声明成局部变量以保持对Timer的引用，否则会被垃圾收集器回收！
        private bool openUp = false;
        private WChatBox _chatbox;
        private string redirect;
        private int m_url;
        private Thread sync;
        private WPersonalInfo _friendInfo;
        private List<Object> _contact_all = new List<object>();
        private List<object> _contact_latest = new List<object>();
        private List<string> _us_na = new List<string>();
        WXService wxs = new WXService();
        private WXUser new_user;
        public static int num = 0;
        public  bool jump = false;
        private int syncnum = 0;   //同步计数  
        private GetIcon gi = new GetIcon();

        private LabSer ls = new LabSer(); //标签操作类
        string ChildName = string.Empty;
        string FriendName = string.Empty;

        public event Closeeventhander Close; 
        public delegate void Closeeventhander( string close );   

        public WinXinBox() {
            InitializeComponent();
            _chatbox = new WChatBox();  //聊天窗口
            _chatbox.Location = new Point(284, 5);
            _chatbox.Size = new Size(874, 626);
            _chatbox.Visible = false;
            Controls.Add(_chatbox);   //添加聊天窗口
            _friendInfo = new WPersonalInfo();  //朋友信息
            _friendInfo.Location = new Point(284, 5);
            _friendInfo.Size = new Size(874, 626);
            _friendInfo.Visible = false;
            Controls.Add(_friendInfo);
            sync1 = new System.Windows.Forms.Timer();
            sync1.Enabled = false;
            _friendInfo.StartChat += new StartChatEventHandler(_friendInfo_StartChat);
            _chatbox.FriendInfoView += new FriendInfoViewEventHandler(wfriendlist_FriendInfoView);
            wChatList1.StartChat += new StartChatEventHandler(_friendInfo_StartChat);

            wFriendsList1.StartChat += new StartChatEventHandler(_friendInfo_StartChat);

        }

        public void Setlogin_redirect(string login_redirect, int _m_url, Auto_Reply_EventHandler dd,string setting,int CanChat) {
            this.redirect = login_redirect;
            this.m_url = _m_url;
            _setting = setting;
            this._Areply = dd;
            this._St_CanChat = CanChat;
        }
        private void WinXinBox_Load(object sender, EventArgs e) {
            // Adddicnull();
            tbc_right.SelectedIndex = 0;
            tbc_right_analysis.SelectedIndex = 0;    
           this.lbxFriendSearch.Visible = false;
            DoMainLogic();
            _Areply.open_close += _Areply_open_close;
            _Areply.Ask_reply += _Areply_Ask_reply;
        }
        /// <summary>
        /// 智能回复开关
        /// </summary>
        /// <param name="open"></param>
        private void _Areply_Ask_reply(bool open,List<string> arr) {
            huifu = open;
            Arr = arr;
        }
        private void _Areply_open_close(bool aotu,List<string> arr) {
            openUp = aotu;
            Arr = arr;
        }

        //  <summary>
        //  好友信息框中点击 聊天
        //   </summary>
        //  <param name = "user" ></ param >
        void _friendInfo_StartChat(WXUser user) {
            new_user = user;
            _chatbox.Visible = true;
         
            tbx_remark.Text = tbx_nickname.Text = tbx_wxaccount.Text = tbx_belong_wx.Text = cb_gender.Text = cbo_age.Text = tb_phone.Text = tb_qq.Text = tb_occupation.Text = tb_dgedu.Text = tb_incoleve.Text = tb_address.Text = tbx_creater.Text = tbx_creatime.Text=string.Empty;

            if (_chatbox != null && _chatbox.Visible == true) {
                _chatbox.Height = this.Height;
                _chatbox.Width = this.Width - 580;
            }
            _chatbox.BringToFront();
            _chatbox.MeUser = _me;
            _chatbox.FriendUser = user;

            Show_Details(user);

            //右侧信息显示
            SearchXinxi sx = EssentialInformationShow;
            sx += RequirenmentAnalysisShow;
            sx += CircleOfFriendsShow;
            sx += ConsumptionAnalysisShow;

            Show(tb_belongkf.Text.Trim(), tbx_nickname.Text, sx);//第一个参数是 ‘微信名’ 第二个参数是 ‘微信好友名’

            //标签显示
            ChildName = _me.NickName;
            FriendName = user.NickName;
            LabelsTextShow(ChildName,FriendName);
        }

        private void Show_Details( WXUser user ) {
            if (user.Sex!=string.Empty) {
                if (user.Sex.Equals("1")) {
                    pic_sex.Image = Properties.Resources.male;
                } else if (user.Sex.Equals("2")) {
                    pic_sex.Image = Properties.Resources.female;
                } else pic_sex.Image = null;
            }
            if (user.City != string.Empty) {
                lblArea.Text = user.City + "，" + user.Province;
            } else {
                lblArea.Text = string.Empty;
            }
            tbx_remark.Text = user.RemarkName;
            tbx_nickname.Text = user.NickName;
            tbx_belong_wx.Text = _me.NickName;
            tb_belongkf.Text = _me.NickName;
            lb_remarknam.Text = user.RemarkName;
            picImage.Image = user.Icon;
            lblNick.Text = user.NickName;

            if (user.Signature != string.Empty) {
                try {
                    lblSignature.Text = user.Signature.Length > 10 ? user.Signature.Substring(0, 10) + "..." : user.Signature.Trim();
                } catch { }
            }
            else{
                lblSignature.Text = string.Empty;
            }
        }

        #region 标签

        //显示标签
        public void LabelsTextShow( string WXName, string FriendName ) {
            if (panel7.Controls.Count > 0)
                panel7.Controls.Clear();
            if (ls.Search(WXName, FriendName) <= 0)
                return;


            List<string> LabList = ls.SearchAll(WXName, FriendName);
            if (LabList[0] == "")
                return;
            Random r = new Random();

            int col1 = 1;
            int col2 = 0;

            if (LabList.Count == 0)
                return;

            int width = 0;
            int height = 0;
            //创建标签
            #region 创建标签
            for (int i = 0; i < LabList.Count; i++) {
                string str = LabList[i].Trim();
                int num = Encoding.Default.GetByteCount(str);
                int num2 = str.Length;
                int num3 = 0;



                foreach (char item in str) {
                    if (Encoding.Default.GetByteCount(item.ToString()) == 1)
                        num3++;
                }
                Label L = new Label();
                L.Name = "Lab" + i.ToString();
                L.Text = str;
                L.BackColor = Color.Transparent;
                #region 字体颜色
                while (true) {
                    col2 = r.Next(1, 7);
                    if (col1 == col2)
                        continue;
                    else {
                        col1 = col2;
                        break;
                    }
                }

                switch (col2) {
                case 1:
                L.ForeColor = Color.Sienna;
                break;
                case 2:
                L.ForeColor = Color.Orange;
                break;
                case 3:
                L.ForeColor = Color.Green;
                break;
                case 4:
                L.ForeColor = Color.LightSeaGreen;
                break;
                case 5:
                L.ForeColor = Color.Blue;
                break;
                case 6:
                L.ForeColor = Color.DarkGreen;
                break;
                }
                #endregion

                L.AutoSize = false;
                L.BorderStyle = BorderStyle.None;
                if (num3 > 0)
                    L.Width = (num) * 10 - num3 * 2 + 24;
                else
                    L.Width = num * 10 - ((num - num2) / 2 * 6) + 24;
                L.Height = 26;
                L.Font = new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
                L.TextAlign = ContentAlignment.MiddleLeft;
                L.Paint += L_Paint;
                if (width + 10 >= panel7.Width - L.Width) {
                    width = 0;
                    height += L.Height + 10;
                }
                L.Location = new Point(10 + width, 10 + height);
                width += L.Width + 10;
                CreateLabelBtn(L, i);
                panel7.Controls.Add(L);
            }
            #endregion

        }

        //重画标签外边框
        private void L_Paint( object sender, PaintEventArgs e ) {
            Borders(e.Graphics, (Label)sender);
        }

        //圆角边框
        private void Borders( Graphics graphics, Label label ) {
            float X = float.Parse(label.Width.ToString()) - 1;
            float Y = float.Parse(label.Height.ToString()) - 1;
            PointF[] points = {
                new PointF(2, 0),
                new PointF(X-2, 0),
                new PointF(X-1, 1),
                new PointF(X, 2),
                new PointF(X, Y-2),
                new PointF(X-1, Y-1),
                new PointF(X-2, Y),
                new PointF(2, Y),
                new PointF(1, Y-1),
                new PointF(0, Y-2),
                new PointF(0, 2),
                new PointF(1, 1)
            };
            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddLines(points);
            Pen pen = new Pen(Color.FromArgb(150, label.ForeColor), 1);
            pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
            graphics.DrawPath(pen, path);
        }

        //创建标签按钮
        private void CreateLabelBtn( Label L, int i ) {
            Label l = new Label();
            l.Name = i.ToString();
            l.Text = "×";
            l.BackColor = Color.Transparent;
            l.ForeColor = L.ForeColor;
            l.AutoSize = false;
            l.BorderStyle = BorderStyle.None;
            //l.Padding = new Padding(3);
            //l.Height = L.Height;
            //l.Width = l.Height;
            l.Font = new Font("微软雅黑", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(134)));
            l.TextAlign = ContentAlignment.MiddleRight;
            l.Location = new Point(L.Width - l.Width, (L.Height - l.Height) / 2);
            l.Click += lab_Click;
            L.Controls.Add(l);
        }

        //标签关闭事件
        void lab_Click( object sender, EventArgs e ) {
            string str = ((Label)sender).Parent.Text;
            ls.Delete(ChildName, FriendName, str);
            LabelsTextShow(ChildName, FriendName);
        }

        #endregion

        /// <summary>
        /// 显示聊天记录
        /// </summary>
        /// <param name="me"></param>
        /// <param name="user"></param>
        public void Showlog(WXUser me, WXUser user) {
            List<WXMsg> msg = new List<WXMsg>();
            richTextBox1.Clear();
            if (user == null) {
                return;
            }
            if (me.NickName != null && user.NickName != null && user.NickName != "") {

                if (sql.GetAllChatLog(me.NickName, user.NickName).Count == 0) {
                    return;
                }
                else {
                    msg = sql.GetChatLog(me.NickName, user.NickName);
                }
                for (int i = msg.Count - 1; i >= 0; i--) {
                    if (msg[i].IsReceive == 0) {
                        richTextBox1.SelectionColor = Color.Blue;
                        richTextBox1.SelectionFont = new Font("微软雅黑", 9, FontStyle.Bold);
                        richTextBox1.AppendText(msg[i].To_NickName + msg[i].Time + "\r\n");
                        richTextBox1.SelectionFont = new Font("微软雅黑", 9, FontStyle.Bold);
                        richTextBox1.SelectionColor = Color.Black;
                        richTextBox1.AppendText(msg[i].Msg + "\r\n");
                    }
                    else {
                        richTextBox1.SelectionColor = Color.Green;
                        richTextBox1.SelectionFont = new Font("微软雅黑", 9, FontStyle.Bold);
                        richTextBox1.AppendText(msg[i].Fr_NickName + msg[i].Time + "\r\n");
                        richTextBox1.SelectionColor = Color.Black;
                        richTextBox1.SelectionFont = new Font("微软雅黑", 9, FontStyle.Bold);
                        richTextBox1.AppendText(msg[i].Msg + "\r\n");
                    }
                }
            }
        }

        /// <summary>
        /// 聊天列表点击好友   开始聊天
        /// </summary>
        /// <param name="user"></param>
        private void wchatlist_StartChat(WXUser user) {
            _chatbox.Visible = true;
            if (_chatbox != null && _chatbox.Visible == true) {
                _chatbox.Height = this.Height - 10;
                _chatbox.Width = this.Width - 279;
            }
            _chatbox.BringToFront();
            _chatbox.MeUser = _me;
            _chatbox.FriendUser = user;
        }

        /// <summary>
        /// 通讯录中点击好友 查看好友信息
        /// </summary>
        /// <param name="user"></param>
        private void wfriendlist_FriendInfoView(WXUser user) {
            if (_friendInfo != null && _friendInfo.Visible == true) {
                _friendInfo.Height = this.Height - 3;
                _friendInfo.Width = this.Width - 279;
            }
            _friendInfo.FriendUser = user;
            _friendInfo.Visible = true;
            _friendInfo.BringToFront();
        }

        /// <summary>
        /// 聊天对话框中点击 好友信息
        /// </summary>
        /// <param name="user"></param>
        void _chat2friend_FriendInfoView(WXUser user) {

            if (_friendInfo != null && _friendInfo.Visible == true) {
                _friendInfo.Height = this.Height - 3;
                _friendInfo.Width = this.Width - 279;
            }
            _friendInfo.FriendUser = user;
            _friendInfo.Visible = true;
            _friendInfo.BringToFront();
        }

        private void CreateChatTab(string tabna) {
            if (!sql.HaveTab(tabna)) {
                sql.CreateNewChatTab(tabna);
            }
            //本地数据库是否有该表
            if (!sqllite.HaveTab("ChatLog"+ MyUin)) {
                sqllite.CreateNewChatTab(MyUin);
            }
        }

        #region 主逻辑
        List<WXUser> contact_all = new List<WXUser>();
        private void DoMainLogic() {
         

            ((Action)(delegate ()  //等待结束
            {
                wxs.SetUser(redirect);
                MyUin = CookieDictionary.GetCookies(redirect + "Wxuin");  //获取我的uin
                JObject init_result = wxs.WxInit(redirect, m_url);  //初始化
                if (init_result != null) {
                    _me = new WXUser();
                    _me.SUrl = m_url;  //是不是少了这个所以没有图像啊
                    _me.LoginRedirect = redirect;
                    _me.UserName = init_result["User"]["UserName"].ToString();
                    _me.NickName = init_result["User"]["NickName"].ToString();
                    _me.HeadImgUrl = init_result["User"]["HeadImgUrl"].ToString();
                    _me.Myuin = MyUin;
                    Success_Login?.Invoke(_me.NickName); //如果登录成功
                
                    Thread getconta = new Thread(GetContact);
                    getconta.Start();
                    foreach (JObject contact in init_result["ContactList"])  //部分好友名单
                    {
                        WXUser user = new WXUser();
                        user.SUrl = m_url;  //是不是少了这个所以没有图像啊
                        user.LoginRedirect = redirect;
                        user.UserName = contact["UserName"].ToString();
                        user.City = contact["City"].ToString();
                        user.HeadImgUrl = contact["HeadImgUrl"].ToString();
                        user.NickName = contact["NickName"].ToString();
                        user.Province = contact["Province"].ToString();
                        user.RemarkName = contact["RemarkName"].ToString();
                        user.Sex = contact["Sex"].ToString();
                        user.Signature = contact["Signature"].ToString();
                        this.BeginInvoke((Action)(delegate () {
                            wChatList1.Items.Add(user);
                        }));
                    }
                    _me.RemarkName = init_result["User"]["RemarkName"].ToString();
                    _me.Sex = init_result["User"]["Sex"].ToString();
                    _me.Signature = init_result["User"]["Signature"].ToString();

                    LoginStatusService ls = new LoginStatusService(); //登陆判断是否有子账户微信登陆表
                    if (ls.SearchLoginChild(_setting, "") == -1)
                        ls.CreateLoginChild(_setting); //没有就创建

                    if (ls.SearchLoginChild(_setting, _me.NickName) == 0)                               //查询是否有登陆记录
                        ls.InsertLoginChild(_setting, _me.NickName);                                        //插入
                    ls.SetLoginChild(_setting, _me.NickName, 1);                                            //设置微信登陆状态
                                                                                                            
                    CreateChatTab(_me.NickName);  //创建数据表
                    List<WXMsg> limsg = new List<WXMsg>();

                    if (_setting != string.Empty) {
                        try {
                          sql.insertWx(_setting, _me.NickName);
                        } catch (Exception e) {
                            WriteLog.Writelog("添加微信到微信个数表", e.ToString());
                        }
                    }
                }
            })).BeginInvoke(null, null);
        }
        #endregion

        #region 页面缩放控制
        protected override void OnResize(EventArgs e) {
            base.OnResize(e);
            Size endSize = this.Size;
            try {
                int percentWidth = endSize.Width / this.Width;
                int percentHeight = endSize.Height / this.Height;
                foreach (Control control in this.Controls) {
                    if (control is DataGridView)
                        continue;
                    //按比例改变控件大小  
                    control.Width = (int)(control.Width * percentWidth);
                    control.Height = (int)(control.Height * percentHeight);
                    pictureBox1.Location = new Point((this.Width / 2-50 ), this.Height / 2-110);  //背景logo
                  //  label1.Location = new Point((this.Width / 2 + 10), (this.Height / 2) + 100);
                    //聊天窗口
                    if (_chatbox != null && _chatbox.Visible == true) {
                        _chatbox.Height = this.Height;
                        _chatbox.Width = this.Width - 580;
                    }
                    if (_friendInfo != null && _friendInfo.Visible == true) {
                        _friendInfo.Height = this.Height;
                        _friendInfo.Width = this.Width - 580;
                    }
                    //为了不使控件之间覆盖 位置也要按比例变化  279
                    control.Left = (int)(control.Left * percentWidth);
                    control.Top = (int)(control.Top * percentHeight);
                }
            }
            catch {}
        }
        #endregion

        private int wchatlist_chiek;

        #region 心跳服务

        /// <summary>
        /// 同步消息线程
        /// </summary>
        private void SyncThead() {
             while (true) {
                SyncMsg();
                syncnum = syncnum + 1;
                try {
                    this.BeginInvoke((Action)delegate () {
                        label1.Text = syncnum.ToString();
                        System.Windows.Forms.Application.DoEvents();
                    });
                }
                catch (Exception) {
                }
                if (jump) {
                    jump = false;
                    Close?.Invoke(_me.NickName);
                    sync.Abort();
                    sync.Join();  //两个结合可以使线程停止
                    break;
                }
                System.Threading.Thread.Sleep(1900);
          }
     }
        /// <summary>
        /// 同步消息
        /// </summary>
        private void SyncMsg() {
            JObject sync_result;   
            sync_result = wxs.WxSync(m_url);  //进行同步
                    if (sync_result != null) {
                        if (sync_result["BaseResponse"]["Ret"].ToString().Equals("0")) {
                            if (sync_result["AddMsgCount"] != null && sync_result["AddMsgCount"].ToString() != "0") {
                        foreach (JObject m in sync_result["AddMsgList"]) {
                                    string msgid = m["MsgId"].ToString();
                                    string from = m["FromUserName"].ToString();
                                    string to = m["ToUserName"].ToString();
                                    string content = m["Content"].ToString();
                                    string txt_url = m["Url"].ToString();
                                    string filename = m["FileName"].ToString();
                                    string mediaid = m["MediaId"].ToString();
                                    string type = m["MsgType"].ToString();
                                    string size = m["FileSize"].ToString();
                                    string status = m["Status"].ToString();
                                   
                                    string v_nickname = m["RecommendInfo"]["NickName"].ToString();
                                    string v_content = m["RecommendInfo"]["Content"].ToString();
                                    string ticket = m["RecommendInfo"]["Ticket"].ToString();
                                    string v_usna = m["RecommendInfo"]["UserName"].ToString();
                                    WXUser picusr = new WXUser();
                                    picusr.LoginRedirect = redirect;
                                    picusr.SUrl = m_url;
                                    picusr.MsgId = msgid;

                                    #region 表情字符串转为GIF格式
                                    //如果接收的消息中有表情则进行转换
                                    string ctent = "";
                                    if (content.IndexOf("[") > -1) {
                                        StringToUrl getUrl = new WChat.StringToUrl();
                                        Regex reg = new Regex(@"\[(.+?)]");
                                        List<string> asd_string = new List<string>();
                                        foreach (Match asd in reg.Matches(content)) {
                                            asd_string.Add(asd.Groups[1].ToString());
                                            for (int i = 0; i < asd_string.Count; i++) {
                                                ctent = content.Replace(asd_string[i], "");
                                            }
                                            content = ctent.Replace("[]", getUrl.GetEmUrl(asd.Groups[1].ToString()));
                                        }

                                    }
                                    #endregion

                                    WXMsg msg = new WXMsg();
                                    msg.MsgId = msgid;
                                    msg.From = from;
                              string contes = "";
                              if (content.Contains("@") && content.Contains(">")) {   //为群内消息
                                string[] _conte = content.Split(':');   //内容
                                    for (int i = 1; i < _conte.Length; i++) {
                                         contes += _conte[i];   //移除了userna，但是有好多<br/>
                                    }
                                    contes = contes.Replace("<br/>","");   //移除<br/>
                              }
                              else {
                                contes = content;
                              }
                                 if (type == "1") {
                                     msg.Msg = contes;
                                  }else if (type == "42") {
                                        msg.Msg = v_nickname;
                                        string big = content.Substring(content.IndexOf("bigheadimgurl") + 15);
                                        msg.bigheadimgurl = big.Substring(0, big.IndexOf("smallheadimgurl") - 2);
                                        string small = content.Substring(content.IndexOf("smallheadimgurl") + 17);
                                        msg.MsgId = small.Substring(0, small.IndexOf("username") - 2);
                                        string Alias = content.Substring(content.IndexOf("alias") + 7);

                                        if (Alias.IndexOf("imagestatus") > 3)
                                            msg.Alias = Alias.Substring(0, Alias.IndexOf("imagestatus") - 2);
                                        else
                                            msg.Alias = string.Empty;

                                        if (msg.Msg.IndexOf("<") != -1)
                                            msg.Msg = WXUser.RemoveHtml(msg.Msg);
                                        if (!System.IO.File.Exists(WChat.path.paths + "\\" + WXUser.RemoveHtml(msg.Msg) + "big.jpg"))
                                            new Card().PicDown(msg.bigheadimgurl, WChat.path.paths + "\\" + WXUser.RemoveHtml(msg.Msg) + "big.jpg");
                                        msg.V_Value = v_usna;//好友串号，添加好友用

                                        msg.Sex = m["RecommendInfo"]["Sex"].ToString();//性别 1男，0女
                                        msg.Province = m["RecommendInfo"]["Province"].ToString();//省份
                                        msg.City = m["RecommendInfo"]["City"].ToString();//城市
                                    }  else if (type == "3") {
                                        msg.Msg = "[图片]";
                                    }
                                    else if (type == "49") {
                                        if (filename == "微信转账") {
                                            msg.Msg = "转账提醒，请在手机上查看";
                                        }
                                        else {
                                            msg.Msg = filename;
                                        }
                                    }
                                    else if (type == "47") {
                                        msg.Msg = "不支持的表情，请在移动设备上查看";
                                    }
                                    else if (type == "37") {
                                        msg.Msg = v_nickname + "想要加你为好友";
                                    } else if (type == "51") {  //屏蔽一些系统数据，他（她）给你留言:"+ v_content && status == "3"
                                        continue;
                                    } else if (type == "10000") {  //为系统信息
                                         msg.Msg = WXUser.RemoveHtml(content); 
                                    } else if (type == "43") {  
                                         msg.Msg = "收到小视频，请在移动设备查看";
                                    } else if (type == "34") {  
                                       msg.Msg = "[语音]";
                                     _me.getvoice(msgid);
                                    } else {
                                       msg.Msg = "不支持的消息请在移动设备上查看";
                                    }
                                      
                                    msg.V_Content = v_content;
                                    msg.V_NickName = v_nickname;
                                    msg.V_UserTicket = ticket;
                                    msg.V_Value = v_usna;

                                    msg.FileName = filename;
                                    msg.FileSize = size;
                                    msg.TxtUrl = txt_url;
                                    msg.MediaId = mediaid;

                                    msg.Readed = false;
                                    msg.Time = DateTime.Now;
                                    msg.To = to;
                                    msg.Type = type;

                                    this.BeginInvoke((Action)delegate () {
                                        WXUser user; bool exist_latest_contact = false;  bool exist_all_contact = false;
                                        foreach (Object u in wChatList1.Items) {                                     //近期好友        
                                            user = u as WXUser;
                                            if (user != null) {
                                                if (user.UserName == msg.From && msg.To == _me.UserName)  //接收别人消息
                                                {
                                                   //  MessageBox.Show("这是消息类型："+msg.Type.ToString()+ "这是消息id："+ msgid);
                                                    msg.Fr_NickName = _me.NickName;
                                                    msg.To_NickName = user.NickName;            
                                                    msg.IsReceive = 0;
                                                    if (content.Contains("@") && content.Contains(">")) {
                                                        string[] us_na = content.Split(':');  //username
                                                        msg.IsGroup = true;      //为群聊
                                                        msg.CrewNickName = _me.Batch_Get_Contact(us_na[0], user.UserName);
                                                        msg.CrewUserName = us_na[0];
                                                    }

                                                    wChatList1.Items.Remove(user);
                                                    wChatList1.Items.Insert(0, user);
                                                    exist_latest_contact = true;
                                                    exist_all_contact = true;
                                                    user.MsgId = msgid;
                                                    user.ReceiveMsg(_me.NickName, msg);
                                                 
                                                    try {
                                                        if (huifu == true) {
                                                            if (Arr.Contains(msg.Fr_NickName)) {
                                                                List<string> keywords_arr = new List<string>();
                                                                if (sql.select_key(_setting)!=null) {  //查到关键词
                                                                    keywords_arr = sql.select_key(_setting);
                                                                    for (int i = 0; i < keywords_arr.Count; i++) {
                                                                        if (msg.Msg.Contains(keywords_arr[i])) {
                                                                            if (sql.select_content(_setting, keywords_arr[i])[0]!=null) {
                                                                                string str = sql.select_content(_setting, keywords_arr[i])[0];
                                                                                reply.Automatic_Reply(user, str, _me, true);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if (Arr != null) {
                                                            if (Arr.Contains(msg.Fr_NickName)) {
                                                                reply.Rebot_Reply(user, msg.Msg, _me, openUp);   //机器人回复
                                                            }
                                                        }
                                                    }catch (Exception e) {
                                                        WriteLog.Writelog("近期好友-同步信息里的Rebot_Reply", e.ToString());
                                                    }
                                                    UnReadMsg?.Invoke(_me.NickName, user.NickName + ":" + msg.Msg);
                                                    break;
                                                }
                                                else if (user.UserName == msg.To && msg.From == _me.UserName)  //同步自己在其他设备上发送的消息
                                                {
                                                    msg.Fr_NickName = _me.NickName;
                                                    msg.To_NickName = user.NickName;
                                                    msg.IsReceive = 1;
                                                    wChatList1.Items.Remove(user);
                                                    wChatList1.Items.Insert(0, user);
                                                    exist_latest_contact = true;
                                                    exist_all_contact = true;
                                                    user.MsgId = msgid;
                                                    user.Syc_SendMsg(_me.NickName, msg );
                                                    try {
                                                        if (Arr != null) {
                                                            if (Arr.Contains(msg.Fr_NickName)) {
                                                                reply.Rebot_Reply(user, msg.Msg, _me, openUp);   //机器人回复
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        WriteLog.Writelog("近期好友-同步信息里发送的Rebot_Reply", e.ToString());
                                                    }
                                                   
                                                    if (UnReadMsg != null) {
                                                        UnReadMsg(_me.NickName, user.NickName + ":" + msg.Msg);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (!exist_latest_contact) {   //不存在最近的列表里
                                            foreach (object o in wFriendsList1.Items) {                                           //所有好友，并非是所有        
                                                WXUser friend = o as WXUser;
                                                if (friend != null && friend.UserName == msg.From && msg.To == _me.UserName) {  //接受消息
                                                    msg.Fr_NickName = _me.NickName;
                                                    msg.To_NickName = friend.NickName;
                                                    msg.IsReceive = 0;

                                                    if (content.Contains("@") && content.Contains(">")) {
                                                        string[] us_na = content.Split(':');  //username
                                                        msg.IsGroup = true;      //为群聊
                                                        msg.CrewNickName = _me.Batch_Get_Contact(us_na[0], friend.UserName);
                                                        msg.CrewUserName = us_na[0];
                                                    }

                                                    wChatList1.Items.Insert(0, friend);
                                                    friend.MsgId = msgid;
                                                    friend.ReceiveMsg(_me.NickName, msg);
                                                    exist_all_contact = true;
                                                    try {
                                                        if (huifu == true) {
                                                            if (Arr.Contains(msg.Fr_NickName)) {
                                                                List<string> keywords_arr = new List<string>();
                                                                if (sql.select_key(_setting) != null) {  //查到关键词
                                                                    keywords_arr = sql.select_key(_setting);
                                                                    for (int i = 0; i < keywords_arr.Count; i++) {
                                                                        if (msg.Msg.Contains(keywords_arr[i])) {
                                                                            if (sql.select_content(_setting, keywords_arr[i])[0] != null) {
                                                                                string str = sql.select_content(_setting, keywords_arr[i])[0];
                                                                                reply.Automatic_Reply(friend, str, _me, true);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        if (Arr != null) {
                                                            if (Arr.Contains(msg.Fr_NickName)) {
                                                                reply.Rebot_Reply(friend, msg.Msg, _me, openUp);   //机器人回复
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        WriteLog.Writelog("同步信息里的Rebot_Reply", e.ToString());
                                                    }
                                                   
                                                    if (UnReadMsg != null) {
                                                        UnReadMsg(_me.NickName, friend.NickName + ":" + msg.Msg);
                                                    }
                                                    break;
                                                }
                                                if (friend != null && friend.UserName == msg.To && msg.From == _me.UserName) {      //发送消息
                                                    msg.Fr_NickName = _me.NickName;
                                                    msg.To_NickName = friend.NickName;
                                                    msg.IsReceive = 1;
                                                    wChatList1.Items.Insert(0, friend);
                                                    friend.MsgId = msgid;
                                                    friend.Syc_SendMsg(_me.NickName, msg);
                                                    exist_all_contact = true;
                                                  
                                                    try {
                                                        if (Arr != null) {
                                                            if (Arr.Contains(msg.Fr_NickName)) {
                                                                reply.Rebot_Reply(friend, msg.Msg, _me, openUp);   //机器人回复
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        WriteLog.Writelog("同步信息里的Rebot_Reply", e.ToString());
                                                    }
                                                    UnReadMsg?.Invoke(_me.NickName, friend.NickName + ":" + msg.Msg);
                                                   break;
                                                }
                                            }
                                        }

                                        if (!exist_all_contact) {   //可能是未加载到好友列表的好友发来的消息，此举是为了防止收不到消息
                                            if (msg.From == _me.UserName) {   //发送消息
                                                JObject bat = wxs.BatchGetContact(msg.To, "", redirect, m_url);
                                                if (bat != null) {
                                                    foreach (var louser in bat["ContactList"]) {
                                                        WXUser lostfriend = new WXUser();
                                                        lostfriend.SUrl = m_url;   //缺少了这个难怪感觉不行呢
                                                        lostfriend.LoginRedirect = redirect;
                                                        lostfriend.UserName = louser["UserName"].ToString();
                                                        lostfriend.NickName = louser["NickName"].ToString();
                                                        lostfriend.Sex = louser["Sex"].ToString();
                                                        lostfriend.HeadImgUrl = louser["HeadImgUrl"].ToString();
                                                        lostfriend.Province = louser["Province"].ToString();
                                                        lostfriend.RemarkName = louser["RemarkName"].ToString();
                                                        lostfriend.City = louser["City"].ToString();

                                                        msg.Fr_NickName = _me.NickName;
                                                        msg.To_NickName = lostfriend.NickName;
                                                        msg.IsReceive = 1;

                                                        wChatList1.Items.Insert(0, lostfriend);
                                                        lostfriend.Syc_SendMsg(_me.NickName, msg);

                                                        try {
                                                            if (Arr != null) {
                                                                if (Arr.Contains(msg.Fr_NickName)) {
                                                                    reply.Rebot_Reply(lostfriend, msg.Msg, _me, openUp);   //机器人回复
                                                                }
                                                            }
                                                        }
                                                        catch (Exception e) {
                                                            WriteLog.Writelog("没有的好友-同步信息里的发送Rebot_Reply", e.ToString());
                                                        }
                                                        UnReadMsg?.Invoke(_me.NickName, lostfriend.NickName + ":" + msg.Msg);
                                                        break;
                                                    }
                                                }
                                            }
                                            if (msg.To == _me.UserName) {   //接受消息
                                                JObject bat = wxs.BatchGetContact(msg.From, "", redirect, m_url);
                                                if (bat != null) {
                                                    foreach (var louser in bat["ContactList"]) {
                                                        WXUser lostfriend = new WXUser();
                                                        lostfriend.SUrl = m_url;   //缺少了这个难怪感觉不行呢
                                                        lostfriend.LoginRedirect = redirect;
                                                        lostfriend.UserName = louser["UserName"].ToString();
                                                        lostfriend.NickName = louser["NickName"].ToString();
                                                        lostfriend.Sex = louser["Sex"].ToString();
                                                        lostfriend.HeadImgUrl = louser["HeadImgUrl"].ToString();
                                                        lostfriend.Province = louser["Province"].ToString();
                                                        lostfriend.RemarkName = louser["RemarkName"].ToString();
                                                        lostfriend.City = louser["City"].ToString();

                                                        msg.Fr_NickName = _me.NickName;
                                                        msg.To_NickName = lostfriend.NickName;
                                                        msg.IsReceive = 0;
                                                        if (content.Contains("@") && content.Contains(">")) {
                                                            string[] us_na = content.Split(':');  //username
                                                            msg.IsGroup = true;      //为群聊
                                                            msg.CrewNickName = _me.Batch_Get_Contact(us_na[0], lostfriend.UserName);
                                                            msg.CrewUserName = us_na[0];
                                                        }

                                                        wChatList1.Items.Insert(0, lostfriend);
                                                        lostfriend.ReceiveMsg(_me.NickName, msg);
                                                        try {
                                                            if (huifu == true) {
                                                                if (Arr.Contains(msg.Fr_NickName)) {
                                                                    List<string> keywords_arr = new List<string>();
                                                                    if (sql.select_key(_setting) != null) {  //查到关键词
                                                                        keywords_arr = sql.select_key(_setting);
                                                                        for (int i = 0; i < keywords_arr.Count; i++) {
                                                                            if (msg.Msg.Contains(keywords_arr[i])) {
                                                                                if (sql.select_content(_setting, keywords_arr[i])[0] != null) {
                                                                                    string str = sql.select_content(_setting, keywords_arr[i])[0];
                                                                                    reply.Automatic_Reply(lostfriend, str, _me, true);
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            if (Arr != null) {
                                                                if (Arr.Contains(msg.Fr_NickName)) {
                                                                    reply.Rebot_Reply(lostfriend, msg.Msg, _me, openUp);   //机器人回复
                                                                }
                                                            }
                                                        } catch (Exception e) {
                                                            WriteLog.Writelog("通讯录里没有的-同步信息里接受的Rebot_Reply", e.ToString());
                                                        }
                                                       
                                                        if (UnReadMsg != null) {
                                                            UnReadMsg(_me.NickName, lostfriend.NickName + ":" + msg.Msg);
                                                        }
                                                        break;
                                                    }
                                                }
                                            }
                                        }

                                        wChatList1.Invalidate();
                                    });
                                }
                            }
                        #region 好友状态更新
                                                 
                        if (sync_result["ModContactCount"] != null && sync_result["ModContactCount"].ToString() != "0") {   //新增联系人
                                foreach (JObject n in sync_result["ModContactList"]) {
                                    WXUser isfriend = new WXUser();

                                    isfriend.SUrl = m_url;   //缺少了这个难怪感觉不行呢
                                    isfriend.LoginRedirect = redirect;
                                    isfriend.UserName = n["UserName"].ToString();
                                    isfriend.NickName = n["NickName"].ToString();
                                    isfriend.Sex = n["Sex"].ToString();
                                    isfriend.HeadImgUrl = n["HeadImgUrl"].ToString();
                                    isfriend.Province = n["Province"].ToString();
                                    isfriend.RemarkName = n["RemarkName"].ToString();
                                    isfriend.City = n["City"].ToString();
                                    isfriend.PYQuanPin = "A";

                                    WXMsg difficulty = new WXMsg();

                                    difficulty.Fr_NickName = _me.NickName;
                                    difficulty.To_NickName = isfriend.NickName;
                                    difficulty.From = n["UserName"].ToString();
                                    difficulty.Msg = "您已将" + n["NickName"].ToString() + "添加到了通讯录，现在可以开始聊天了";  //只接受文本消息
                                    difficulty.Readed = false;
                                    difficulty.Time = DateTime.Now;
                                    difficulty.To = _me.UserName;
                                    difficulty.IsReceive = 0;
                                    difficulty.Type = "1";

                                try {
                                    if (sql.Select_send_devices(_me.NickName, n["NickName"].ToString())) {
                                        sql.update_new_friend(_me.NickName, n["NickName"].ToString(), "37", 1);
                                    }
                                }
                                catch (Exception e) {
                                    WriteLog.Writelog("ModContact", e.ToString());
                                }
                                this.BeginInvoke((Action)delegate () {
                                    bool in_friend_list = false;
                                    WXUser friend = null;
                                    if (isfriend != null) {
                                        for (int i = 0; i < wFriendsList1.Items.Count; i++) {
                                            friend = wFriendsList1.Items[i] as WXUser;   //好友列表里的
                                            if (friend!=null) {
                                                if (friend.UserName == isfriend.UserName) {
                                                    in_friend_list = true;
                                                }
                                            }
                                        }
                                        if (!in_friend_list) {  //如果不在我的好友列表里
                                            wChatList1.Items.Insert(0, isfriend);
                                            wFriendsList1.Items.Add(isfriend);
                                            reply.Rebot_Reply(user, difficulty.Msg, _me, openUp);
                                        }
                                    }
                                    wChatList1.Invalidate();
                                    wFriendsList1.Invalidate();
                                });
                            }
                         }
                        #endregion
                    }
                    else {
                        jump = true;  // 跳出循环
                        }
                    }
        }
        #endregion

        /// <summary>
        /// 自创的排序方法来自于冒泡排序法
        /// By：李大亮 2017/5/14
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private List<WXUser> MySort( List<WXUser> user ) {
            WXUser t;
            for (int j = 1; j < user.Count; j++) {
                for (int i = 0; i < user.Count - j; i++) {

                    if (user[i].SortTag() > user[i + 1].SortTag()) {   //如果比后一位大则往前排
                        t = user[i];
                        user[i] = user[i + 1];
                        user[i + 1] = t;
                    }
                    if (char.IsDigit(user[i].SortTag())) {   //如果是数字则往前排

                        t = user[i];
                        user[i] = user[i + 1];
                        user[i + 1] = t;
                    }
                    if (!char.IsLetter(user[i].SortTag())) {   //如果不是字母则往前排
                        t = user[i];
                        user[i] = user[i + 1];
                        user[i + 1] = t;
                    }
                }
            }
            return user;
        }
        Dictionary<string, Dictionary<string, List<WXUser>>> WXLogin = new Dictionary<string, Dictionary<string, List<WXUser>>>();
        Dictionary<string, List<WXUser>> dic = new Dictionary<string, List<WXUser>>();
        private void Adddicnull() {
            for (int i = 0; i < 26; i++) {
                dic.Add(Convert.ToChar(65+i).ToString(), null);
            }
        }
        /// <summary>
        /// 获取我的好友
        /// </summary>
        private void GetContact() {
             get_contact: JObject contact_result = null;
             contact_result = wxs.GetContact(redirect, Seq, m_url); //通讯录
            if (contact_result != null) {
                foreach (JObject contact in contact_result["MemberList"])  //完整好友名单
                {
                    WXUser user = new WXUser();
                    user.SUrl = m_url;   //缺少了这个难怪感觉不行呢
                    user.LoginRedirect = redirect;
                    user.UserName = contact["UserName"].ToString();
                    user.City = contact["City"].ToString();
                    user.HeadImgUrl = contact["HeadImgUrl"].ToString();
                    user.NickName = contact["NickName"].ToString();
                    user.Province = contact["Province"].ToString();
                    user.PYQuanPin = contact["PYQuanPin"].ToString();
                    user.PYInitial = contact["PYInitial"].ToString();
                    user.RemarkName = contact["RemarkName"].ToString();
                    user.RemarkPYQuanPin = contact["RemarkPYQuanPin"].ToString();
                    user.Sex = contact["Sex"].ToString();
                    user.Signature = contact["Signature"].ToString();
                    user.VerifyFlag = contact["VerifyFlag"].ToString();
                    user.AttrStatus = contact["AttrStatus"].ToString();
                    user.ContactFlag = contact["ContactFlag"].ToString();

                    contact_all.Add(user);
       
                    try {
                        if (user.VerifyFlag == "0" && !user.UserName.Contains("@@")) {
                            if (user.UserName != "filehelper") {  //大陆微信去除文件传输助手
                                sql.InsertMyFriendTab(_setting, _me.UserName, _me.NickName, user.UserName, user.ShowName, user.Sex, user.Province);
                            }
                        }
                    } catch (Exception e) {
                        WriteLog.Writelog("getcontact", e.ToString());
                    }
                }
                WriteLog.Writelog("getcontact", contact_result["Seq"].ToString());
                Seq = int.Parse(contact_result["Seq"].ToString());   //标志联系人是否加载完毕
                if (Seq != 0) {
                    goto get_contact;  
                }
            }
            //IOrderedEnumerable<object> list_all = contact_all.OrderBy(e => (e as WXUser).ShowPinYin);
            WXUser wx; string start_char;

            //Thread ssd = new Thread(new ThreadStart(sd));
            //ssd.IsBackground = true;
            //ssd.Start();

            List<WXUser> Sorted = MySort(contact_all);
            //gi.BatchDownloadIcon(Sorted);
            foreach (object o in Sorted) {
                wx = o as WXUser;
                start_char = wx.ShowPinYin == "" ? "#" : wx.ShowPinYin.Substring(0, 1);
                if (!_contact_all.Contains(start_char.ToUpper())) {
                    _contact_all.Add(start_char.ToUpper());   // 添加拼音
                }
                _contact_all.Add(o);  // 添加联系人
            }
            try {
                this.BeginInvoke((Action)(delegate ()  //等待结束
                {
                    wFriendsList1.gicon = gi;
                     wFriendsList1.Items.AddRange(_contact_all.ToArray());  //通讯录
                    _friendInfo.FriendUser = _me;
                    if (NewAllMsg != null) { NewAllMsg(_me, user); } //群发专用委托
                    sync = new Thread(SyncThead);
                    sync.IsBackground = true;
                    sync.Start();
                }));
            }
            catch (Exception e) {
                WriteLog.Writelog("getcontact", e.ToString());
            }
        }

        #region 杂项

        private void 删除项目ToolStripMenuItem_Click( object sender, EventArgs e ) {
            if (wChatList1.Items.Count != 0) {
                wChatList1.Items.RemoveAt(wchatlist_chiek);
            }
        }
        /// <summary>
        /// 获取点击的索引
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void wChatList1_MouseUp( object sender, MouseEventArgs e ) {
            if (wChatList1 != null && wChatList1.IndexFromPoint(e.X, e.Y) != 65535) {
                int index = wChatList1.IndexFromPoint(e.X, e.Y);
                wChatList1.SelectedIndex = index;
                if (wChatList1.SelectedIndex != -1) {
                    wchatlist_chiek = wChatList1.SelectedIndex;
                }
            }
        }
        /// <summary>
        /// 当控件需要重绘时调整控件的大小
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WinXinBox_Paint( object sender, PaintEventArgs e ) {

            if (_chatbox != null && _chatbox.Visible == true) {
                _chatbox.Height = this.Height;
                _chatbox.Width = this.Width - 580;
            }
        }

        #endregion

        #region 数据分析-右侧备注区

        /// <summary>
        /// 添加标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 添加标签ToolStripMenuItem_Click( object sender, EventArgs e ) {
            string nickname = ChildName;
            if (nickname == string.Empty) { MessageBox.Show("请选择好友"); return; }
            AddLabels al = new AddLabels(nickname,FriendName);
            al.wxb = this;
            al.Show();
        }

        /// <summary>
        ///  右侧获取聊天记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinTabControl1_SelectedIndexChanged( object sender, EventArgs e ) {
            if (tbc_right.SelectedIndex == 3)
                Showlog(_me, new_user);
        }

        /// <summary>
        /// 委托
        /// </summary>
        /// <param name="WXName"></param>
        /// <param name="FriendName"></param>
        /// <param name="sx"></param>
        private void Show( string WXName, string FriendName, SearchXinxi sx ) {
            sx(WXName, FriendName);
        }
        private delegate void SearchXinxi( string WXName, string FriendName );

        #region 查询数据
        private void EssentialInformationShow( string WXName, string FriendName ) {

            EssentialInformationService eis = new EssentialInformationService();
            try {
                if (eis.SearchAll(WXName, FriendName) > 0) {
                    EssentialInformation ei = eis.Show(WXName, FriendName);

                    tbx_remark.Text = ei.RemarksName;
                    tbx_nickname.Text = ei.NickName;
                    tbx_wxaccount.Text = ei.AccountNumber;
                    tbx_belong_wx.Text = ei.The;
                    cb_gender.Text = ei.Sex;
                    cbo_age.Text = ei.Old;
                    daTiPicker_brith.Value = ei.DateOfBirth;
                    tb_phone.Text = ei.Telephone;
                    tb_qq.Text = ei.QQ;
                    tb_occupation.Text = ei.Occupation;
                    tb_dgedu.Text = ei.Culture;
                    tb_incoleve.Text = ei.IncomeLevel;
                    tb_address.Text = ei.Address;
                    tb_belongkf.Text = ei.TheCustomer;
                    //cb_classification.Text;
                    tb_remarks.Text= ei.Remarks;
                    tbx_creater.Text= ei.CreatePeople;
                    tbx_creatime.Text = ei.SetTime;
                }
                
            }
            catch (Exception) {

                throw;
            }
        }
        private void RequirenmentAnalysisShow( string WXName, string FriendName ) {
            RequirenmentAnalysisService ras = new RequirenmentAnalysisService();

            if (ras.SearchAll(WXName, FriendName) > 0) {
                RequirenmentAnalysis ra = ras.Show(WXName, FriendName);

                tbx_req_now.Text = ra.CurrentDemand;
                tbx_potential_demand.Text = ra.PotentialDemand;
                tbx_custom1.Text = ra.Custom1;
                tbx_custom2.Text = ra.Custom2;
                tbx_custom3.Text = ra.Custom3;
            }
            else
                tbx_req_now.Text = tbx_potential_demand.Text = tbx_custom1.Text = tbx_custom2.Text = tbx_custom3.Text = string.Empty;

        }
        private void CircleOfFriendsShow( string WXName, string FriendName ) {
            CircleOfFriendsService cofs = new CircleOfFriendsService();

            if (cofs.SearchAll(WXName, FriendName) > 0) {
                CircleOfFriends cof = cofs.Show(WXName, FriendName);

                tbx_tim_li_like.Text = cof.COFLike;
                tbx_tim_li_acti_tim.Text = cof.ActiveTime.ToString();
                tbx_tim_li_persanaly.Text = cof.PPAnalysis;
                tbx_tim_li_cost1.Text = cof.Custom1;
                tbx_tim_li_cost2.Text = cof.Custom2;
                tbx_tim_li_cost3.Text = cof.Custom3;
            }
            else
                tbx_tim_li_like.Text = tbx_tim_li_acti_tim.Text = tbx_tim_li_persanaly.Text = tbx_tim_li_cost1.Text = tbx_tim_li_cost2.Text = tbx_tim_li_cost3.Text = string.Empty;
        }
        private void ConsumptionAnalysisShow( string WXName, string FriendName ) {
            ConsumptionAnalysisService cas = new ConsumptionAnalysisService();

            if (cas.SearchAll(WXName, FriendName) > 0) {
                ConsumptionAnalysis ca = cas.Show(WXName, FriendName);

                tbx_standard_consump.Text = ca.CStandard;
                tbx_con_hab.Text = ca.CHabit;
                tbx_Cosmetic_tendency.Text = ca.BrandOrientation;
                tbx_buy_cosmetic_now.Text = ca.BrandOName;
                tbx_buy_skinca_now.Text = ca.SkincareBrand;
                tbx_sk_care_brand_tenden.Text = ca.BrandSName;
                tbx_cloth_tendency.Text = ca.ClothingBrandTendency;
                tbx_buy_clothes_now.Text = ca.RecentlyPurchasedClothes;
                tbx_Ornaments_tendency.Text = ca.JewelryBrandTendency;
                tbx_buy_ornaments_now.Text = ca.RecentlyPurchasedJewelry;
                tbx_comprehensive_analy.Text = ca.ComprehensiveAnalysis;
            }
            else
                tbx_standard_consump.Text = tbx_con_hab.Text = tbx_Cosmetic_tendency.Text = tbx_buy_cosmetic_now.Text = tbx_buy_skinca_now.Text = tbx_sk_care_brand_tenden.Text = tbx_cloth_tendency.Text = tbx_buy_clothes_now.Text = tbx_Ornaments_tendency.Text = tbx_buy_ornaments_now.Text = tbx_comprehensive_analy.Text = string.Empty;
        }
        #endregion

        #region 信息保存
        /// <summary>
        /// 基本信息保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbn_basic_save_Click(object sender, EventArgs e) {
            if (tbx_nickname.Text.Equals(string.Empty)) {
                MessageBox.Show("请选择客户!");
            }else {
                EssentialInformationService eis = new EssentialInformationService();
                if (eis.HaveTab(tb_belongkf.Text.Trim())==-1) { eis.CreateTable(tb_belongkf.Text.Trim()); }
                EssentialInformation ei = new EssentialInformation();
                ei.RemarksName = tbx_remark.Text.Trim();
                ei.NickName = tbx_nickname.Text.Trim();
                ei.AccountNumber = tbx_wxaccount.Text.Trim();
                ei.The = tbx_belong_wx.Text.Trim();
                ei.Sex = cb_gender.Text.Trim();
                ei.Old = cbo_age.Text.Trim();
                ei.DateOfBirth = daTiPicker_brith.Value;
                ei.Telephone = tb_phone.Text.Trim();
                ei.QQ = tb_qq.Text.Trim();
                ei.Occupation = tb_occupation.Text.Trim();
                ei.Culture = tb_dgedu.Text.Trim();
                ei.IncomeLevel = tb_incoleve.Text.Trim();
                ei.Address = tb_address.Text.Trim();
                ei.TheCustomer = tb_belongkf.Text.Trim();
                //cb_classification.Text;
                ei.Remarks = tb_remarks.Text.Trim();
                ei.CreatePeople = tbx_creater.Text.Trim();
                ei.SetTime = tbx_creatime.Text.Trim();

                switch (eis.SearchAll(tb_belongkf.Text.Trim(), tbx_nickname.Text))//第一个参数是 ‘微信名’ 第二个参数是 ‘微信好友名’
                {
                case -1:
                case 0:
                if (eis.Insert(ei, tb_belongkf.Text.Trim()) > 0)
                    MessageBox.Show("添加完成");
                break;

                default:
                if (eis.Set(ei, tb_belongkf.Text.Trim(), tbx_nickname.Text) > 0)
                    MessageBox.Show("更新完成");
                break;
                }
            }
        }
        /// <summary>
        /// 保存需求信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_requirement_save_Click(object sender, EventArgs e) {
            if (tbx_nickname.Text.Equals(string.Empty)) {
                MessageBox.Show("请选择客户!");
            }else {
                RequirenmentAnalysisService res = new RequirenmentAnalysisService();
                RequirenmentAnalysis rea = new RequirenmentAnalysis();
                if (res.HaveTab(tb_belongkf.Text.Trim())==-1) { res.CreateRequirenmentAnalysis(tb_belongkf.Text.Trim()); }
                rea.FriendName = tbx_nickname.Text;
                rea.CurrentDemand = tbx_req_now.Text;
                rea.PotentialDemand = tbx_potential_demand.Text;
                rea.Custom1 = tbx_custom1.Text;
                rea.Custom2 = tbx_custom2.Text;
                rea.Custom3 = tbx_custom3.Text;

                switch (res.SearchAll(tb_belongkf.Text.Trim(), tbx_nickname.Text))//第一个参数是 ‘微信名’ 第二个参数是 ‘微信好友名’
                {
                case -1:
                case 0:
                if (res.Insert(rea, tb_belongkf.Text.Trim()) > 0)
                    MessageBox.Show("添加完成");
                break;

                default:
                if (res.Set(rea, tb_belongkf.Text.Trim(), tbx_nickname.Text) > 0)
                    MessageBox.Show("更新完成");
                break;
                }
            }
        }
        /// <summary>
        /// 保存朋友圈分析信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_time_lin_save_Click(object sender, EventArgs e) {
            tbx_tim_li_acti_tim.Text = DateTime.Now.ToString();
            CircleOfFriendsService cfs = new CircleOfFriendsService();
            CircleOfFriends cof = new CircleOfFriends();
            if (tb_belongkf.Text.Trim()!= string.Empty) {
                try {
                    if (cfs.HaveTab(tb_belongkf.Text.Trim())==-1)
                        cfs.CreateCircleOfFriends(tb_belongkf.Text.Trim());
                }
                catch (Exception ex){
                    WriteLog.Writelog("不存在表则建表", ex.ToString());
                }
            }
            if (tbx_nickname.Text.Trim() != string.Empty) {
                cof.FriendName = tbx_nickname.Text;
                cof.COFLike = tbx_tim_li_like.Text;
                cof.ActiveTime = DateTime.Now;
                cof.PPAnalysis = tbx_tim_li_persanaly.Text;
                cof.Custom1 = tbx_tim_li_cost1.Text;
                cof.Custom2 = tbx_tim_li_cost2.Text;
                cof.Custom3 = tbx_tim_li_cost3.Text;

                switch (cfs.SearchAll(tb_belongkf.Text.Trim(), tbx_nickname.Text))//第一个参数是 ‘微信名’ 第二个参数是 ‘微信好友名’
                {
                case -1:
                case 0:
                if (cfs.Insert(cof, tb_belongkf.Text.Trim()) > 0)
                    MessageBox.Show("添加完成");
                break;

                default:
                if (cfs.Set(cof, tb_belongkf.Text.Trim(), tbx_nickname.Text) > 0)
                    MessageBox.Show("更新完成");
                break;
                }
            }
            else {
                MessageBox.Show("请选择客户");
            }
        }
        /// <summary>
        /// 保存消费分析信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_consumption_save_Click(object sender, EventArgs e) {
            if (tbx_nickname.Text.Equals(string.Empty)) {
                MessageBox.Show("请选择客户");
            } else {
                ConsumptionAnalysisService cas = new ConsumptionAnalysisService();
                ConsumptionAnalysis ca = new ConsumptionAnalysis();
                if (tb_belongkf.Text.Trim() !=string.Empty) {
                    try {
                        if (cas.HaveTab(tb_belongkf.Text.Trim())==-1)
                        cas.CreateConsumptionAnalysis(tb_belongkf.Text.Trim());
                    } catch (Exception ex) {
                        WriteLog.Writelog("不存在表则建表", ex.ToString());
                    }
                }
                    ca.FriendName = tbx_nickname.Text;
                    ca.CStandard = tbx_standard_consump.Text;
                    ca.CHabit = tbx_con_hab.Text;
                    ca.BrandSName = tbx_Cosmetic_tendency.Text;
                    ca.BrandOrientation = tbx_Cosmetic_tendency.Text;
                    ca.BrandOName = tbx_buy_cosmetic_now.Text;  ////////////////////
                    ca.SkincareBrand = tbx_sk_care_brand_tenden.Text;
                    ca.BrandSName = tbx_buy_clothes_now.Text;
                    ca.ClothingBrandTendency = tbx_cloth_tendency.Text;     ////////////////////
                    ca.RecentlyPurchasedClothes = tbx_buy_clothes_now.Text;
                    ca.JewelryBrandTendency = tbx_Cosmetic_tendency.Text;  //饰品倾向
                    ca.RecentlyPurchasedJewelry = tbx_buy_ornaments_now.Text;
                    ca.ComprehensiveAnalysis = tbx_comprehensive_analy.Text;

                    switch (cas.SearchAll(tb_belongkf.Text.Trim(), tbx_nickname.Text)) {
                    case 0:
                    if (cas.Insert(ca, tb_belongkf.Text.Trim()) > 0)
                        MessageBox.Show("添加完成");
                    break;

                    default:
                    if (cas.Set(ca, tb_belongkf.Text.Trim(), tbx_nickname.Text) > 0)
                        MessageBox.Show("更新完成");
                    break;
                    }
            }
        }
        #endregion

        #endregion

        #region 搜索好友
        //搜索好友
        private void SearchFriends()
        {
            string searchfriend = this.txtSearch.Text.Trim();
            if (!searchfriend.Equals(string.Empty)) {
                this.lbxFriendSearch.Items.Clear();
                foreach (WXUser item in contact_all) {
                    if (item.AttrStatus.Equals("0") || item.AttrStatus.Equals("4"))
                        continue;
                    //搜索备注中的文字
                    if (item.PYInitial.Contains(searchfriend) || item.RemarkName.Contains(searchfriend) || item.RemarkPYQuanPin.Contains(searchfriend)) {
                        if (this.lbxFriendSearch.Visible == false)
                            this.lbxFriendSearch.Visible = true;

                        if (item.RemarkName != "")
                            lbxFriendSearch.Items.Add(item.RemarkName);
                        else
                            lbxFriendSearch.Items.Add(item.NickName);
                        continue;
                    }//搜索昵称中的文字
                    else if (WXUser.RemoveHtml(item.NickName).Contains(searchfriend) || WXUser.RemoveHtml(item.PYQuanPin).Contains(searchfriend)) {
                        if (this.lbxFriendSearch.Visible == false)
                            this.lbxFriendSearch.Visible = true;

                        this.lbxFriendSearch.Items.Add(WXUser.RemoveHtml(item.NickName));
                    }
                }
            }
            else
                this.lbxFriendSearch.Visible = false;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchFriends();
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            SearchFriends();
        }

        //搜索好友列表双击事件
        private void lbxFriendSearch_DoubleClick(object sender, EventArgs e)
        {
            if (lbxFriendSearch.SelectedItem == null)
                return;

            WXUser w = new WXUser();
            string Nick = lbxFriendSearch.SelectedItem.ToString();
            foreach (WXUser item in contact_all) {
                if (item.RemarkName == Nick) {
                    w = item;
                }
                else if (WXUser.RemoveHtml(item.NickName) == Nick)
                    w = item;
            }
            this.txtSearch.Text = string.Empty;
            this.lbxFriendSearch.Visible = false;
            this.lbxFriendSearch.Items.Clear();
            foreach (WXUser item in wChatList1.Items) {
                if (w.NickName == item.NickName || item.RemarkName == w.RemarkName) {
                    wChatList1.Items.Remove(item);
                    tabc_left.SelectedIndex = 0;
                    break;
                }
            }
            wChatList1.Items.Insert(0, w);
            _friendInfo_StartChat(w);
        }

        //在通讯录中查找好友
        private WXUser addZuijin(string FriendName)
        {
            WXUser w = new WXUser();
            foreach (WXUser item in contact_all)
            {
                if(item.NickName.Equals(FriendName))
                {
                    w = item;
                    break;
                }
            }
            return w;
        }

        #endregion
      
    }
}